// lib/pages/login_page.dart
import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _phoneController = TextEditingController();
  bool _isLoading = false;

Future<void> _handleLogin() async {
  final phone = _phoneController.text.trim();
  //debugPrint('输入手机号: $phone');
  if (phone.isEmpty) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('请输入手机号'))
    );
    return;
  }

  setState(() => _isLoading = true);

  try {
    // 查询用户是否存在
    final response = await Supabase.instance.client
        .from('users')
        .select()
        .eq('phone_number', phone);

    if (!mounted) return; // 👈 保护 context

    //debugPrint('查询结果: $response');

    if (response.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('用户不存在'))
      );
    } else {
      Navigator.pushReplacementNamed(context, '/home');
    }
  } catch (e) {
    if (!mounted) return; // 👈 保护 context
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('登录失败: ${e.toString()}'))
    );
  } finally {
    if (mounted) setState(() => _isLoading = false);
  }
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('手机号登录')),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            TextField(
              controller: _phoneController,
              decoration: const InputDecoration(
                labelText: '手机号码',
                hintText: '请输入11位手机号',
                prefixIcon: Icon(Icons.phone),
              ),
              keyboardType: TextInputType.phone,
              maxLength: 11,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _isLoading ? null : _handleLogin,
              style: ElevatedButton.styleFrom(
                minimumSize: const Size(double.infinity, 50),
              ),
              child: _isLoading 
                  ? const CircularProgressIndicator()
                  : const Text('立即登录'),
            ),
          ],
        ),
      ),
    );
  }
}